//
//  PictureShowViewController.swift
//  Gaoloumi
//
//  Created by Jasper on 4/16/16.
//  Copyright © 2016 Jasper. All rights reserved.
//

import UIKit
import MJRefresh
import SVProgressHUD
import AVOSCloud

class PictureShowViewController: RootViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, SDPhotoBrowserDelegate {

    @IBOutlet weak var collectionView: UICollectionView!
    
    var pictureArray = [Picture]()
    var tower: Tower?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = tower?.name
        
        let flowLayout = UICollectionViewFlowLayout()
        collectionView.collectionViewLayout = flowLayout
        
        collectionView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            self.requestData(false)
        })
        
        requestData(true)
//        createData()
    }
    
    func createData() {
        let picture = Picture()
        let data = try? Data(contentsOf: URL(fileURLWithPath: (Bundle.main.path(forResource: "defaultImg", ofType: "jpg"))!))
        let file = AVFile(name: "defaultImg.jpg", data: data!)
        picture.file = file
        picture.name = tower?.name
        picture.descriptions = ""
        picture.tower = tower
        
        picture.saveInBackground { (succed: Bool, error: Error?) in
            if succed {
                
            } else {
                SVProgressHUD.showError(withStatus:error?.localizedDescription)
            }
        }
    }
    
    func requestData(_ header: Bool) {
        
        SVProgressHUD.show()
        let query: AVQuery = Picture.query()
        query.whereKey(kPictureKeyTower, equalTo: tower)
        query.whereKey(kPictureKeyIsShow, equalTo: true)
        query.includeKey(kPictureKeyFile)
        query.order(byDescending: "createdAt")
        let limitPage = 18
        query.limit = limitPage
        
        if !header {
            let top = pictureArray.last
            let date = top?.object(forKey: "createdAt")
            if date != nil {
                query.whereKey("createdAt", lessThan: date)
            } else {
                query.whereKey("createdAt", lessThan: Date())
            }
        }
        
        query.findObjectsInBackground { (objects: [Any]?, error: Error?) in
            if error == nil && objects != nil {
                if let picture = objects as? [Picture] {
                    SVProgressHUD.dismiss()
                    self.pictureArray += picture
                    self.collectionView.reloadData()
                } else {
                    SVProgressHUD.showError(withStatus: "获取列表失败")
                }
            } else {
                SVProgressHUD.showError(withStatus:error?.localizedDescription)
            }
            
            if objects != nil && (objects?.count)! < limitPage {
                self.collectionView.mj_footer.endRefreshingWithNoMoreData()
                
            } else {
                if header {
                    self.collectionView.mj_footer.resetNoMoreData()
                } else {
                    self.collectionView.mj_footer.endRefreshing()
                }
            }
        }
    }
    

    // MARK: UICollectionViewDelegate
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let intWidth = (UIScreen.main.bounds.width - 42)/3
        return CGSize(width: intWidth, height: intWidth)
    }
   
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(10, 10, 10, 10)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        return 20
       return pictureArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // PictureCollectionViewCell
        
         let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PictureCollectionViewCell", for: indexPath) as! PictureCollectionViewCell
        let picture = pictureArray[(indexPath as NSIndexPath).row]
        cell.refreshView(picture)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = (indexPath as NSIndexPath).item
        photoBrowser.imageCount = pictureArray.count
        photoBrowser.sourceImagesContainerView = collectionView
        photoBrowser.show()
    }
    
    
    // MARK:SDPhotoBrowserDelegate
    
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        let indexPath = IndexPath(item: index, section: 0)
        let cell = self.collectionView.cellForItem(at: indexPath) as? PictureCollectionViewCell
        if cell != nil {
           return cell!.pictureImgView.image
        }
        return nil
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let url = pictureArray[index].file!.url
        return URL(string: url!)
    }
    
    @IBAction func submitPicClicked(_ sender: UIBarButtonItem) {
        
        if AVUser.current() == nil { // 没登录
            let storyboard = UIStoryboard(name: "Main", bundle: nil);
            let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController");
            self.navigationController?.pushViewController(loginViewController, animated: true)
        } else {
            let storyboard = UIStoryboard(name: "Main", bundle: nil);
            let submitPicVC = storyboard.instantiateViewController(withIdentifier: "SubmitPictureViewController") as! SubmitPictureViewController;
           submitPicVC.tower = tower
            self.navigationController?.pushViewController(submitPicVC, animated: true)
        }
    }
}










